import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import QtQuick.Controls.Material


Pane {
    id: root
    Layout.fillWidth: true
    Layout.fillHeight: true
    padding: 20

    property alias basePromptInput: basePromptInput
    property alias outputArea: outputArea
    property alias dynamicFieldsModel: dynamicFieldsModel

    signal composeClicked(string finalPrompt, var historyItem)

    // 弹窗组件实例
    PromptPopup {
        id: promptPopup
        anchors.centerIn: parent

        onPromptSelected: function(selectedPrompt) {
            if (promptPopup.fieldIndex >= 0 && promptPopup.fieldIndex < dynamicFieldsModel.count) {
                var currentFieldRow = fieldsRepeater.itemAt(promptPopup.fieldIndex)
                var currentText = currentFieldRow.currentValueText || ""
                var newValue = ""
                
                if (selectedPrompt === "") {
                    newValue = ""
                } else {
                    if (currentText.trim() === "") {
                        newValue = selectedPrompt
                    } else {
                        newValue = currentText + ", " + selectedPrompt
                    }
                }
                
                currentFieldRow.updateValueText(newValue)
                dynamicFieldsModel.setProperty(promptPopup.fieldIndex, "value", newValue)
                promptPopup.currentValue = newValue
            }
        }
    }

    ColumnLayout {
        anchors.fill: parent
        spacing: 16

        Label {
            text: qsTr("Base Prompt")
            font.bold: true
        }
        TextField {
            id: basePromptInput
            Layout.fillWidth: true
            Layout.preferredHeight: 40
            placeholderText: qsTr("Enter base prompt here")
            background: Rectangle {
                color: "#333"
                radius: 4
            }
        }

        ListModel {
            id: dynamicFieldsModel
            ListElement { label: "人物 (Character)"; value: ""; placeholder: "e.g., Suzuki Masaru" }
            ListElement { label: "镜头 (Camera)"; value: ""; placeholder: "e.g., close-up, wide shot" }
            ListElement { label: "服饰 (Apparel)"; value: ""; placeholder: "e.g., red dress, leather jacket" }
            ListElement { label: "表情 (Expression)"; value: ""; placeholder: "e.g., smiling, sad" }
            ListElement { label: "动作 (Action)"; value: ""; placeholder: "e.g., running, jumping" }
            ListElement { label: "场景 (Scene)"; value: ""; placeholder: "e.g., in a forest, on a beach" }
        }

        ScrollView {
            Layout.fillWidth: true
            Layout.preferredHeight: 200
            clip: true
            ColumnLayout {
                id: fieldsColumn
                spacing: 8
                Repeater {
                    id: fieldsRepeater  // 添加一个id
                    model: dynamicFieldsModel
                    FieldRow {
                        labelText: model.label
                        valueText: model.value
                        placeholder: model.placeholder
                        onRemoveClicked: dynamicFieldsModel.remove(index)
                        onPopupClicked: {
                            promptPopup.fieldIndex = index
                            promptPopup.openPopup(model.label, currentValueText)
                        }
                        onClearClicked: {
                            dynamicFieldsModel.setProperty(index, "value", "")
                            if (promptPopup.visible && promptPopup.fieldIndex === index) {
                                promptPopup.currentValue = ""
                            }
                        }
                    }
                }
                Button {
                    text: "+"
                    Layout.alignment: Qt.AlignHCenter
                    onClicked: dynamicFieldsModel.append({label: "New Field", value: "", placeholder: "Enter value"})
                }
            }
        }

        Button {
            id: composeButton
            text: qsTr("合成 (Compose)")
            Layout.alignment: Qt.AlignHCenter
            Material.background: Material.accent
            onClicked: {
                var promptParts = [basePromptInput.text];
                var historyItem = {
                    basePrompt: basePromptInput.text,
                    timestamp: new Date().toLocaleString(),
                    dynamicFields: []
                };

                var userPrompts = fileHelper.loadUserPrompts();

                for (var i = 0; i < dynamicFieldsModel.count; i++) {
                    var item = dynamicFieldsModel.get(i);
                    if (item.value.trim() !== '') {
                        promptParts.push(item.value.trim());

                        // 自动保存新的用户提示词
                        var category = item.label;
                        var promptsForCategory = userPrompts[category] || [];
                        var defaultPrompts = promptPopup.getPromptsForField(category); // 获取包含默认值的完整列表
                        var allKnownPrompts = defaultPrompts.concat(promptsForCategory);

                        var values = item.value.split(',').map(v => v.trim()).filter(v => v !== '');
                        values.forEach(function(val) {
                            if (allKnownPrompts.indexOf(val) === -1) {
                                fileHelper.saveUserPrompt(category, val);
                            }
                        });
                    }
                    historyItem.dynamicFields.push({ label: item.label, value: item.value });
                }
                var finalPrompt = promptParts.filter(p => p.trim() !== '').join(', ');
                outputArea.text = finalPrompt;
                historyItem.prompt = finalPrompt;
                composeClicked(finalPrompt, historyItem);
            }
        }

        Label {
            text: qsTr("Generated Prompt:")
            font.bold: true
        }
        TextArea {
            id: outputArea
            Layout.fillWidth: true
            Layout.preferredHeight: 120
            readOnly: true
            wrapMode: Text.WrapAnywhere
            background: Rectangle {
                color: "#333"
                radius: 4
            }
        }
    }
}
